#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstring>
//读写锁版本


typedef struct
{
    int code;       //账户号码
    double balance; //账户的余额
    //定义一把互斥锁，对多线程操i做的账户进行加锁
    // pthread_mutex_t mutex;
} Account;

class Ac
{
public:
    Ac() = default;
    explicit Ac(const double total); //防止隐式类型转化

    double deposit(const double amt);
    double check();
    double withdraw(double amt);
    ~Ac();

private:
    Account *account;
    pthread_rwlock_t rwlock;
};

Ac::Ac(double total)
{
    account = new Account();
    account->balance = total;
    account->code = 1001;
    pthread_rwlock_init(&rwlock, NULL);
}

//存钱
double Ac::deposit(double amt)
{

    pthread_rwlock_wrlock(&rwlock);
    if (amt < 0)
    {
        pthread_rwlock_unlock(&rwlock);
        return 0.0;
    }

    //这是存储之后的额度
    double money = account->balance + amt;

    account->balance = money;
    pthread_rwlock_unlock(&rwlock);
    return amt;
}

double Ac::withdraw(double amt)
{   
    //写锁
    pthread_rwlock_wrlock(&rwlock);
    if (amt < 0 || amt > account->balance)
    {

        pthread_rwlock_unlock(&rwlock);
        return 0.0;
    }

    pthread_rwlock_unlock(&rwlock);
}

//查询
double Ac::check()
{   //d读锁
    pthread_rwlock_rdlock(&rwlock);

    if (account->balance < 0)
    {
        pthread_rwlock_unlock(&rwlock);
        return 0.0;
    }

    std::cout << "余额：" << account->balance << std::endl;

    pthread_rwlock_unlock(&rwlock);
}

Ac::~Ac()
{
    pthread_rwlock_destroy(&rwlock);
    delete account;
}